/**
 * @Title: SystemLoginController.java
 * @Package com.camelot.cmis.login
 * Copyright: Copyright (c) 2013
 * Company:北京柯莱特科技有限公司
 * @author Comsys-dengzongyu
 * @date 2013-12-18 下午9:30:00
 * @version V1.0
 */

package com.camelot.ccr.login.controller;

import java.io.IOException;
import java.util.Enumeration;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.camelot.ccr.global.controller.BaseController;
import com.camelot.ccr.global.exception.BusinessException;
import com.camelot.ccr.global.util.Md5;
import com.camelot.ccr.global.util.Utility;
import com.camelot.ccr.system.dao.UserDao;
import com.camelot.ccr.system.persistence.User;

/**
 * <pre>
 * 系统登陆控制
 * </pre>
 * @author Liu Jun
 * @version V0.1, 2013-12-30 下午8:49:08
 */
@Controller
@RequestMapping("/login")
public class SystemLoginController extends BaseController {

	@Resource
	private UserDao userDao;
	/**
	 * <pre>
	 * 登录校验
	 * </pre>
	 * @param userName 用户名
	 * @param userPwd 密码
	 * @param session session对象
	 * @author Liu Jun, 2013-12-30 下午8:49:31
	 * @throws BusinessException 异常
	 */
	@RequestMapping("/systemLogin")
	public String systemLoginInit(String userName,String userPwd,HttpSession session) throws BusinessException{
		userPwd = Md5.getEncryptedPwd(userPwd);
		User u = userDao.validatorLogin(userName, userPwd);
		if(Utility.isNotNull(u)){
			session.setAttribute("user", u);
			
			return "/center";
		}
		return "../../login";
	}
	
	
	@RequestMapping("/center")
	public String homePage(){
		return "/center";
	}
	
	@RequestMapping("/updatePwd")
	public String updatePwd(){
		return "/usermanage/updatePwd";
	}
	
	/**
	 * <pre>
	 * 退出登陆，清除session存储
	 * </pre>
	 * @param session session全局
	 * @param response response
	 * @author dengzongyu, 2014-1-16 下午3:06:05
	 * @throws IOException 异常
	 */
	@RequestMapping("/systemOutLogin")
	public String systemLoginOut(HttpServletResponse response ,HttpSession session) throws IOException{
		Enumeration<String> em = session.getAttributeNames();
		while(em.hasMoreElements()){
			session.removeAttribute(em.nextElement().toString());
		}
		session.invalidate();
		return "redirect:/login.jsp";
	}
	
	@RequestMapping("/savePwd")
	public String savePwd(HttpServletResponse response ,HttpServletRequest request,HttpSession session) throws IOException{
		String password = request.getParameter("password");
		String newPwd = request.getParameter("newPwd");
		
		User user = userDao.findById(((User)session.getAttribute("user")).getId());
		user.setUserpwd(Md5.getEncryptedPwd(newPwd));
		
		userDao.saveOrUpdate(user);
		return "redirect:/login/center";
	}
	
}

